package cn.id68.www.http.cookie.store;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import okhttp3.Cookie;
import okhttp3.HttpUrl;

/**
 * Created by Administrator on 2017/3/21.
 */

public class MemoryCookieStore implements CookieStore{

    private final HashMap<String,List<Cookie>> allCookie = new HashMap<>();

    @Override
    public void add(HttpUrl uri, List<Cookie> cookies) {
        List<Cookie> oldCooks = allCookie.get(uri.host());
        if (oldCooks != null){
            Iterator<Cookie> itNew = cookies.iterator();
            Iterator<Cookie> itOld = oldCooks.iterator();
            while (itNew.hasNext()){
                String va = itNew.next().name();
                while (va != null && itOld.hasNext()){
                    String v = itOld.next().name();
                    if (v != null && va.equals(v)){
                        itOld.remove();
                    }
                }
            }
            oldCooks.addAll(cookies);
        }else {
            allCookie.put(uri.host(),cookies);
        }
    }

    @Override
    public List<Cookie> get(HttpUrl uri) {

        List<Cookie> cookies = allCookie.get(uri);
        if (cookies == null){
            cookies = new ArrayList<>();
            allCookie.put(uri.host(),cookies);
        }
        return cookies;
    }

    @Override
    public List<Cookie> getCookies() {
        List<Cookie> cookies = new ArrayList<>();
        Set<String> httpUrls = allCookie.keySet();
        for (String url: httpUrls){
            cookies.addAll(allCookie.get(url));
        }
        return cookies;
    }

    @Override
    public boolean remove(HttpUrl uri, Cookie cookie) {

        List<Cookie> cookies = allCookie.get(uri.host());

        if (cookies!=null){
            return cookies.remove(cookie);
        }
        return false;
    }

    @Override
    public boolean removeAll() {
        allCookie.clear();
        return true;
    }
}
